package org.langcom;

import java.net.URL;
import java.util.HashSet;
import java.util.Set;

public class CompositeClassLoader extends ClassLoader {

	private Set<ClassLoader> loaders = new HashSet<ClassLoader>();

	public CompositeClassLoader(ClassLoader parent) {
		super(parent);
	}

	public CompositeClassLoader(ClassLoader...classLoaders) {
		super(classLoaders[0]);
		for (int i = 1; i < classLoaders.length; i++) {
			add(classLoaders[i]);
		}
	}

	public CompositeClassLoader(Class...classes) {
		super(classes[0].getClassLoader());
		for (int i = 1; i < classes.length; i++) {
			add(classes[i].getClassLoader());
		}
	}

	public ClassLoader add(ClassLoader classLoader) {
		if (classLoader != null) {
			loaders.add(classLoader);
		}
		return this;
	}

	@Override
	public Class<?> loadClass(String name) throws ClassNotFoundException {
		for (ClassLoader classLoader : loaders) {
			try {
				return classLoader.loadClass(name);
			} catch (ClassNotFoundException e) {
				continue;
			}
		}
		return getParent().loadClass(name);
	}

	@Override
	public URL getResource(String name) {
		for (ClassLoader classLoader : loaders) {
			URL resource = classLoader.getResource(name);
			if (resource != null) {
				return resource;
			}
			continue;
		}
		return getParent().getResource(name);
	}

}
